package com.example.list.service_demo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.list.R;

import java.util.logging.Logger;

public class BindServiceActivity extends AppCompatActivity implements View.OnClickListener {


    MyService myservice;
    private class MyServiceConnection implements ServiceConnection {

        public MyServiceConnection(){}
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder binder) {
            myservice = ((MyService.MyBinder)binder).getService();
            Log.d("service","1111111111");
//绑定成功后调用
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
//当服务奔溃时调用
            Log.d("service","00000000");
        }


    }
    Intent intent;
    MyServiceConnection conn;
    private boolean isSuccess;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_service);
        findViewById(R.id.sa_bindservice).setOnClickListener(this);
        findViewById(R.id.sa_unbindservice).setOnClickListener(this);
        findViewById(R.id.sa_playball).setOnClickListener(this);
        findViewById(R.id.sa_playPoker).setOnClickListener(this);



    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sa_bindservice:
//绑定一个Service
                if (!isSuccess) {
                    intent = new Intent(this, MyService.class);
                    conn = new MyServiceConnection();
                    isSuccess = this.bindService(intent, conn, Context.BIND_AUTO_CREATE);
                }
                break;
            case R.id.sa_unbindservice:
                if (conn != null) {
                    this.unbindService(conn);
                    conn = null;
                    isSuccess = false;
                }
                break;

            case R.id.sa_playball:
                if (conn!=null) {
                    myservice.playBall();
                }else {
                    Toast.makeText(this, "service 未绑定", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.sa_playPoker:
                if (conn!=null) {
                    myservice.playPoker();
                }else {
                    Toast.makeText(this, "service 未绑定", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

}

